package erfgame.core.world.terrain.factory;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.GZIPInputStream;


import erfgame.core.world.terrain.TerrainUpdateFactory;
import erfgame.core.world.terrain.TerrainUpdateGroup;
import erfgame.core.world.terrain.file.TerrainUpdateSerializer;

public class SerializedTerrainUpdateFactory implements
		TerrainUpdateFactory {
	
	private static final Logger log = Logger.getLogger( SerializedTerrainUpdateFactory.class.getName() );
	
	private URL resourceURL;
	
	public SerializedTerrainUpdateFactory( String resourcePath ) {
		this( SerializedTerrainUpdateFactory.class.getResource( resourcePath ) );
	}
	
	public SerializedTerrainUpdateFactory( URL url ) {
		this.resourceURL = url;
	}

	public TerrainUpdateGroup createTerrainUpdate() {
		TerrainUpdateGroup update;
		InputStream ins = null;
		try {
			ins = resourceURL.openStream();
			if( ins != null ) {
				ins = new GZIPInputStream(ins);
				update = TerrainUpdateSerializer.deserializeGroup(ins);
			} else {
				throw new RuntimeException( "no such resource "+resourceURL );
			}
		} catch( Exception ex ) {
			throw new RuntimeException( ex );
		} finally {
			if( ins != null ) {
				try {
					ins.close();
				} catch( IOException ex ) {
					log.log( Level.WARNING, "unable to close "+resourceURL, ex );
				}
			}
		}
		return update;
	}
	

}
